package com.wswy.wyjk.ui.main.choose

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.Space
import android.widget.TextView
import com.google.android.flexbox.AlignContent
import com.google.android.flexbox.FlexboxLayout
import com.my.httpapi.api.baseMyView.IosAlertDialog
import com.raft.framework.base.RFBaseActivity
import com.raft.framework.utils.RxUtils
import com.raft.framework.utils.UICompat
import com.tencent.mmkv.MMKV
import com.wswy.wyjk.AppContext
import com.wswy.wyjk.R
import com.wswy.wyjk.api.MMKVConstant
import com.wswy.wyjk.core.App
import com.wswy.wyjk.core.location.LocManager
import com.wswy.wyjk.core.location.LocationModel
import com.wswy.wyjk.model.CityModel
import com.wswy.wyjk.model.LicenseType
import com.wswy.wyjk.model.LocalConfig
import com.wswy.wyjk.ui.EXTRA_DATA
import com.wswy.wyjk.ui.REQUEST_CODE_CHOOSE_CITY
import com.wswy.wyjk.ui.common.Router
import com.wswy.wyjk.ui.main.WebViewActivity
import com.wswy.wyjk.ui.main.event.CarType
import com.wswy.wyjk.utils.ToastUtils
import com.wswy.wyjk.utils.gone
import com.wswy.wyjk.utils.visible
import kotlinx.android.synthetic.main.activity_practice_type.*
import org.greenrobot.eventbus.EventBus
import timber.log.Timber

class PracticeTypeActivity : RFBaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_practice_type)

        initViews()
    }


    private val currentLocalConfig = LocalConfig()

    private fun initViews() {


        rl_choose_city.setOnClickListener {
            Router.start(this, Router.CHOOSE_CITY)
        }

        tv_submit.setOnClickListener {

            if (currentLocalConfig.cityName.isNullOrEmpty()) {
                ToastUtils.showText("请选择城市")

                return@setOnClickListener
            }

            val toMain = App.getPracticeContext() == null

            App.saveConfig(currentLocalConfig)

            if (toMain) {
                Router.start(this, Router.MAIN)
            } else {
                EventBus.getDefault().post(CarType(currentLocalConfig.carType))
            }
            MMKV.defaultMMKV().encode(MMKVConstant.POSITION, 0)
            finish()
        }


        App.getPracticeContext()?.let {

            tv_city.text = it.cityName

            currentLocalConfig.cityName = it.cityName
            currentLocalConfig.areaCode = it.areaCode.toIntOrNull() ?: 0

            currentLocalConfig.carType = it.licenseType.typeName
        } ?: let {

            LocManager.getInstance()
                .requestAndLoad(this, object : LocManager.OnRequestLocationCallback {
                    override fun onGetLocation(locationModel: LocationModel?) {
                        locationModel?.let {

                            Timber.e(it.toString())

                            if (!isFinishing) {
                                allCity(it.city)
                            }
                        }

                    }

                    override fun onError(msg: String?) {
                    }

                })

        }


        flex_types.removeAllViewsInLayout()

        flex_types.alignContent = AlignContent.FLEX_START

        val lineMaxItem = 4
        val rowHeight = UICompat.dp2px(104)

        val values = LicenseType.values()

        values.forEachIndexed { index, licenseType ->
            val inflate = LayoutInflater.from(this)
                .inflate(R.layout.layout_item_choose_type, flex_types, false)

            val lp = FlexboxLayout.LayoutParams(0, FlexboxLayout.LayoutParams.WRAP_CONTENT)

            inflate.findViewById<ImageView>(R.id.img_type).setImageResource(licenseType.icon)

            inflate.findViewById<TextView>(R.id.tv_type_title).text = licenseType.title

            inflate.setTag(R.id.item_data, licenseType)
            inflate.setOnClickListener(itemTypeClickListener)

            if (TextUtils.isEmpty(licenseType.typeAbbr)) {
                inflate.findViewById<TextView>(R.id.tv_type_abbr).gone()
            } else {
                inflate.findViewById<TextView>(R.id.tv_type_abbr).let {
                    it.visible()
                    it.text = licenseType.typeAbbr
                }
            }


            if (TextUtils.equals(currentLocalConfig.carType, licenseType.typeName)) {
                currTypeLayout = inflate
                inflate.isSelected = true
            } else {
                inflate.isSelected = false
            }


            lp.flexGrow = 1f

            if (index > 0 && index % lineMaxItem == 0) {
                lp.isWrapBefore = true
            }

            flex_types.addView(inflate, lp)
        }

        val remain = values.size % lineMaxItem

        if (remain > 0) {
            val lp = FlexboxLayout.LayoutParams(0, rowHeight)

            lp.flexGrow = (lineMaxItem - remain).toFloat()
            flex_types.addView(Space(this), lp)
        }

        if (currTypeLayout == null) {
            currTypeLayout = flex_types.getChildAt(0)?.also {
                it.isSelected = true
            }
        }

        updateSelected()
    }


    private var currTypeLayout: View? = null

    private val itemTypeClickListener = View.OnClickListener {

        if (it != currTypeLayout) {

            currTypeLayout?.isSelected = false

            currTypeLayout = it

            currTypeLayout?.isSelected = true

            updateSelected()
        }

    }

    private fun updateSelected() {

        (currTypeLayout?.getTag(R.id.item_data) as? LicenseType)?.let {

            tv_practice_type_hint.text = getString(R.string.practice_type_hint, it.title)

            currentLocalConfig.carType = it.typeName

        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_CITY) {
            data?.getParcelableExtra<CityModel?>(EXTRA_DATA)?.let {

                Timber.e("$it")

                allCity(it.name)

            }

        }

    }

    @SuppressLint("CheckResult")
    private fun allCity(city: String) {
        if (isFinishing) return

        tv_city.text = city

        LocManager.getInstance().getCityInfo(city).compose(RxUtils.io2main()).subscribe { t1, t2 ->

            t1?.orNull()?.let {
                Timber.e("${it}")

                currentLocalConfig.cityName = city
                currentLocalConfig.areaCode = it.adCode?.toIntOrNull() ?: 0

            } ?: kotlin.run {

                currentLocalConfig.areaCode = 0
                t2?.printStackTrace()
            }

        }
    }
}